<template>
  <s-dynamic-form
    ref="dynamicForm"
    :form="fakeValue"
    :items="items"
    :disable-item="disabled"
    @change="$itemChange"
  >
    <template #item="{ properties, type }">
      <slot name="item" :properties="properties" :type="type"></slot>
    </template>
  </s-dynamic-form>
</template>

<script>
export default {
  name: 'DynamicFormPanel',
  props: {
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    formId: {
      type: String,
      required: false
    },
    modelValue: {
      type: Object
    }
  },
  emits: ['change', 'update:modelValue', 'save'],
  data() {
    return {
      fakeValue: this.modelValue || {},
      items: []
    }
  },
  watch: {
    modelValue: {
      handler: function (val, oldVal) {
        this.fakeValue = val
      },
      deep: true
    }
  },
  created() {
    if (this.formId) {
      this.$loading(true)
      this.$loadDynamicForm(this.formId)
        .then((res) => {
          this.$loading(false)
          if (!res.data) {
            this.$message.warn('表单不存在')
          } else {
            this.items = res.data.moduleForm.data
          }
        })
        .catch(() => {
          this.$loading(false)
        })
    }
  },
  methods: {
    $itemChange(val) {
      this.$emit('change', val)
      this.$emit('update:modelValue', this.fakeValue)
    }
  }
}
</script>

<style lang="less" scoped></style>
